<template>
  <div class="dropdown" ref="dropdownRef">
    <button
      class="btn btn-outline-light dropdown-toggle"
      :class="{ show: isOpen }"
      type="button"
      @click.prevent="handleClickDropdown"
    >
      {{ title }}
    </button>
    <ul class="dropdown-menu mt-1" :class="{ show: isOpen }">
      <slot></slot>
    </ul>
  </div>
</template>
<script lang="ts">
import { defineComponent, ref, watch, onUnmounted } from 'vue'
import useClickOutside from '@/hooks/useClickOutside'
import bus from '@/plugins/bus'
export default defineComponent({
  name: 'Dropdown',
  props: {
    title: {
      type: String,
      required: true
    }
  },
  setup() {
    const isOpen = ref(false)
    const dropdownRef = ref<null | HTMLElement>(null)
    const isClickOutside = useClickOutside(dropdownRef)
    watch(isClickOutside, () => {
      if (isOpen.value && isClickOutside.value) {
        isOpen.value = false
      }
    })
    const handleClickDropdown = () => {
      isOpen.value = !isOpen.value
    }

    const handleItemClick = (boo: boolean) => {
      isOpen.value = boo
    }
    bus.on('dropdown-item-click', handleItemClick)
    onUnmounted(() => {
      bus.off('dropdown-item-click', handleItemClick)
    })
    return {
      isOpen,
      dropdownRef,
      handleClickDropdown
    }
  }
})
</script>
